package dao.impl;
import dao.IUserDao;
import entity.User;

public class UserDaoImpl implements IUserDao{
	User[] users;
	User loginUser;
	
	public UserDaoImpl(){
		users = new User[10];
	}
	
	private int getUseFulIndex(){
		for (int i = 0; i < users.length; i++) {
			if(users[i] == null){
				return i;
			}
		}
		return users.length;
	}
	
	@Override
	public boolean save(User user) {
		int index = this.getUseFulIndex();
		if(-1 == index){
			return false;
		}
		for (int i = 0; i < index; i++) {
			if(users[i].getAccount().getId() == user.getAccount().getId()){
				return false;
			}
		}
		users[index] = user;
		return true;
	}

	@Override
	public boolean delete(User user) {
		return false;
	}

	@Override
	public boolean update(User user) {
		return false;
	}

	@Override
	public User selectById(int id) {
		return null;
	}

	@Override
	public User[] selectAll() {
		return null;
	}

	@Override
	public boolean login(User user) {
		int index = this.getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if(users[i].getAccount().getId() == user.getAccount().getId() && users[i].getAccount().getPassword().equals(user.getAccount().getPassword())){
				loginUser = users[i];
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean regsit(User user) {
		return save(user);
	}

	@Override
	public boolean deposit(double money) {
		if(money >= 0){
			loginUser.getAccount().setMoney(loginUser.getAccount().getMoney() + money);
			return true;
		}
		return false;
	}

	@Override
	public boolean withdrawals(double money) {
		if(money >= 0 && loginUser.getAccount().getMoney() >= money){
			loginUser.getAccount().setMoney(loginUser.getAccount().getMoney() - money);
			return true;
		}
		return false;
	}

	@Override
	public boolean transfer(double money, int id) {
		int index = this.getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if(users[i].getAccount().getId() == id){
				users[i].getAccount().setMoney(users[i].getAccount().getMoney() + money);
				loginUser.getAccount().setMoney(loginUser.getAccount().getMoney() - money);
				return true;
			}
		}
		return false;
	}

	@Override
	public User selectInformation() {
		return loginUser;
	}
	
}
